import React, { useState, useEffect } from 'react';
import { Form, Input, Button, message } from 'antd';
import { fakeLogin } from '../api/user';
import { useNavigate } from 'react-router-dom';
import { useUserStore } from '../store/user';

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { token } = useUserStore();

  // 检查登录状态
  useEffect(() => {
    if (token) {
      navigate('/home');
    }
  }, [token, navigate]);

  const setUserInfo = useUserStore((state) => state.setUserInfo);

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      const res: any = await fakeLogin(values);
      if (res.status === 200) {
        const { userId, token, userName, admin, nickName, avatarUrl } = res.data.data;
        setUserInfo(userId, token, userName, admin, nickName, avatarUrl);
        message.success('登录成功');
        navigate('/home');
      } else {
        message.error(res.data.msg || '登录失败');
      }
    } catch (e) {
      message.error('网络错误');
    }
    setLoading(false);
  };

  return (
    <Form form={form} onFinish={onFinish} style={{ maxWidth: 300, margin: '0 auto', marginTop: 100 }} initialValues={{ username: '911', password: '123456' }}>
      <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}> 
        <Input placeholder="用户名" />
      </Form.Item>
      <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}> 
        <Input.Password placeholder="密码" />
      </Form.Item>
      
      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading} block>登录</Button>
      </Form.Item>
      <Form.Item>
        <Button type="link" block onClick={() => navigate('/register')}>没有账号？去注册</Button>
      </Form.Item>
      <Form.Item>
        <Button type="dashed" block onClick={() => form.setFieldsValue({ username: '111111', password: '111111' })}>管理员登录</Button>
      </Form.Item>
    </Form>
  );
};

export default Login; 